import { useMutation } from "react-relay";
import {useCallback, useContext, useState} from "react";
import {
  ConnectionHandler,
  RecordSourceSelectorProxy,
  RecordProxy
} from "relay-runtime";
import { DeviceCommonInput } from "./__generated__/useCreateDeviceMutation.graphql";
import {UserContext} from "../routing/UserContext";

const graphql = require("babel-plugin-relay/macro");

//这个特别！返回{TodoEdge, User} 而不是直接返回TodoNode: Todo就可以了。!多出两个麻烦。
const mutation = graphql`
  mutation useCreateDeviceMutation($type: String!,$inp:DeviceCommonInput!) {
      newEQP(type:$type,inp: $inp) {
        id cod oid type sort vart
        ... on Elevator {
          flo
        }
      }
  }
`;

//TS不允许使用in作为回调函数参数名！所以graphQl接口参数名in不能用啊
export default function useCreateDeviceMutation() {
  const [result, setResult] =useState(false);
  const [commit, isInFlight] = useMutation(mutation);
  return {
    call:useCallback(
      (type: string, inp:DeviceCommonInput) => {
             //上面回调参数是 组件编辑器触发发过来的(text, userId)=>{};
        return commit({
          variables: {
            type, inp
          },
          updater: (store: RecordSourceSelectorProxy) => {
            const payload = store.getRootField("newEQP");
            if (!payload) {
              return;
            }
            const retEqpId: any = payload.getValue("id");
            setResult(retEqpId);
            //sharedUpdater(store, userId, deletedIds);
          },
          //optimisticUpdater: (store: RecordSourceSelectorProxy) => {        }
        });
      },
      [commit]
    ),
    isInFlight,
    result
  };
}
